const {
    comMysql
  } = require("../db/mysql")
  const xss = require("xss")
  
  const addChat = (req, res) => {
    let {
      username,
      content,
    } = req.query
    content = xss(content)
    let time = new Date().getTime()
    let sql = `insert into chatRoom(username,content,time) values(?,?,?)`
    let arr = [username, content, time]
    return comMysql(sql, arr)
  }
  
  const delChat = (req, res) => {
    let {
      id,
      username
    } = req.query
    let sql = `delete from chatRoom where id = ? and username = ?`
    let arr = [id, username]
    return comMysql(sql, arr)
  }
  
  const searchChat = (req, res) => {
    let sql = `select chatRoom.content,chatRoom.time,chatRoom.id,users.avatar,users.realname,users.id as "UserId" from chatRoom LEFT JOIN users on chatRoom.username = users.username`
    return comMysql(sql)
  }
  
  const searchLastChat = (req,res)=>{
    let sql =  `SELECT
      chatRoom.content,
      users.avatar,
    users.realname,
    users.username
  FROM
      chatRoom
  LEFT JOIN users ON chatRoom.username = users.username
  ORDER BY
      chatRoom.time DESC
  LIMIT 1`
    return comMysql(sql)
  }
  
  module.exports = {
    addChat,
    delChat,
    searchChat,
    searchLastChat
  }